package com.spbdx.framework.web.service;

import com.spbdx.common.constant.CacheConstants;
import com.spbdx.common.constant.Constants;
import com.spbdx.common.core.domain.entity.SysUser;
import com.spbdx.common.core.domain.model.LoginBody;
import com.spbdx.common.core.domain.model.LoginUser;
import com.spbdx.common.core.redis.RedisCache;
import com.spbdx.common.exception.ServiceException;
import com.spbdx.common.exception.user.CaptchaException;
import com.spbdx.common.exception.user.CaptchaExpireException;
import com.spbdx.common.exception.user.UserPasswordNotMatchException;
import com.spbdx.common.utils.DateUtils;
import com.spbdx.common.utils.MessageUtils;
import com.spbdx.common.utils.ServletUtils;
import com.spbdx.common.utils.StringUtils;
import com.spbdx.common.utils.ip.IpUtils;
import com.spbdx.framework.manager.AsyncManager;
import com.spbdx.framework.manager.factory.AsyncFactory;
import com.spbdx.framework.security.context.AuthenticationContextHolder;
import com.spbdx.framework.security.context.UsernamePhoneAuthenticationToken;
import com.spbdx.system.service.ISysConfigService;
import com.spbdx.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 登录校验方法
 *
 * @author cms
 */
@Slf4j
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Resource
    private Environment environment;

    // 是否允许账户多终端同时登录（true允许 false不允许）
    @Value("${token.soloLogin}")
    private boolean soloLogin;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        if (!soloLogin) {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey)) {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public String loginTel(LoginBody loginBody) {
        String username = loginBody.getUsername();

        //验证手机号和邮箱是否符合格式或者是否为空
//        boolean isPhone = false;
        //先判断是手机号还是邮箱登录
        if (StringUtils.isNotEmpty(loginBody.getTel())) {
            if (Pattern.compile("^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$").matcher(loginBody.getTel()).matches()) {
                username = loginBody.getTel();
            } else {
                throw new ServiceException("登录失败,手机号格式不正确!");
            }
        } else {
            throw new ServiceException("登录失败,手机号不能为空!");
        }

        //在判断是密码还是验证码登录
        boolean isPassword = false;
        if (StringUtils.isNotEmpty(loginBody.getPassword())) {
            isPassword = true;
        } else if (StringUtils.isNotEmpty(loginBody.getCode())) {
            isPassword = false;
        } else {
            throw new ServiceException("登录失败,密码和验证码不能同时为空!");
        }
        boolean test = isTest();

        //验证码验证
        if (!isPassword) {
            //测试环境
            String codeKey = CacheConstants.CAPTCHA_CODE_KEY + loginBody.getTel();
            String value = redisCache.getCacheObject(codeKey);
            if (test && StringUtils.isEmpty(value)) {
                value = "111111";
            }
            if (StringUtils.isNotEmpty(value)) {
                if (!value.equals(loginBody.getCode())) {
                    throw new ServiceException("验证码错误!");
                } else {
                    redisCache.deleteObject(codeKey);
                }
            } else {
                throw new ServiceException("验证码错误!");
            }
        }
        // 用户验证
        Authentication authentication = null;
        try {
            if (isPassword) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());
                AuthenticationContextHolder.setContext(authenticationToken);
                // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                authentication = authenticationManager.authenticate(authenticationToken);
            } else {
                // 该方法会去调用UsernamePhoneUserDetailsServiceImpl.loadUserByUsername
                authentication = authenticationManager.authenticate(new UsernamePhoneAuthenticationToken(loginBody.getTel()));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        if (!soloLogin) {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey)) {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public boolean isTest() {
        try {
            Set<String> activeProfiles = Arrays.stream(environment.getActiveProfiles()).collect(Collectors.toSet());
            log.info("activeProfiles:{}", activeProfiles);
            return activeProfiles.contains("test");
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }
}
